package org.esgi.dns.record;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
public class Record {
	private String mainFolder = "D:\\DNS\\";
	private long ttl = 3600;
	private FileRecord domaineInfoGetORCreate(String domaine)throws Exception{
		try {
			String [] split = domaine.split("\\.");
			String folder = split[split.length -1]; 
			String serverName = null; 
			if(domaine.startsWith("www")){
				serverName = split [split.length -2];
			}else{
				serverName = domaine.substring(0, domaine.length() - folder.length() -1);
			}
			File path = new File(mainFolder+folder);
			if(!path.exists())
				path.mkdirs();
			FileRecord ft = new FileRecord(mainFolder+folder+"\\"+serverName,true);
			if(null!=ft.getSection("TTL")){
				@SuppressWarnings("unchecked")
				List<String> list = (List<String>)ft.getSection("TTL");
				String sttl = list.get(0);
				if(null!=sttl){
					Long ttl = Long.valueOf(sttl);
					if(new Date().getTime() >=ttl)
						return ft;
				}
			}
			//Map<String, List<String>> results = new HashMap<String,List<String>>( 15 );
			Hashtable<String,String> env = new Hashtable<String,String>();
			env.put( "java.naming.factory.initial","com.sun.jndi.dns.DnsContextFactory" );
			DirContext ictx = new InitialDirContext(env);
			Attributes attrs = ictx.getAttributes(domaine);
			for (NamingEnumeration<? extends Attribute> e = attrs.getAll(); e.hasMoreElements(); ){
				Attribute a = (Attribute) e.nextElement();
				List<String> tmp = new ArrayList<String>();
				int size = a.size();
				for ( int i = 0; i < size; i++ )
					tmp.add( (String) a.get( i ) );
				ft.putProperty(a.getID(),tmp);
				//results.put(a.getID(), tmp);
			} 
			List<String> tmp = new ArrayList<String>();
			long time = (new Date()).getTime();
			tmp.add(String.valueOf(time+ttl));
			ft.putProperty("TTL",tmp);
			ft.saveFile();
			return ft;
		} catch (NamingException e) {
			e.printStackTrace();
			return null;
		}

	}
	public static void main(String[] args) throws Exception{	
		new Record().domaineInfoGetORCreate("www.facebook.com");
	}

}
